package com.yxy.utils;

import com.yxy.base.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yuxiaoyang
 * @Date 2020-06-03
 * 唯一订单号生成器
 */
@Service
@Slf4j
public class FieldNoGenerator {
  @Autowired
  private JdbcTemplate jdbcTemplate;

  /**
   * 生成唯一的 类订单号
   * 例如 LY20200624000003
   * 参数type: 例如LY, JC,必须为2位大写字符串
   * noIndex宽度为 6位
   */
  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
  public String generator(String type) throws Exception {
    //当前日期的年月日,要取数据库时间
    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    String nowDate = sf.format(new Date());

    String sql = " select * from unique_key where type = '" + type + "' for update "; //锁定读
    List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
    if (result.size() == 0 || result.size() > 1) {
      throw new BusinessException(506, "unique_key表中没有相应的type,或者有多个type--->" + type);
    }
    // 获取当前no
    String currentNo = result.get(0).get("no").toString();
    String dbDate = currentNo.substring(2, 10); //数据库中的订单号日期
    String noIndex = currentNo.substring(11);

    String newNo;
    if (!nowDate.equals(dbDate)) { //不相等 则替换成nowDate,且初始化noIndex
      newNo = type + nowDate + "000001";
    } else { //相等, 则 noIndex++
      DecimalFormat countFormat = new DecimalFormat("000000");
      String noIndexAfter = countFormat.format(Integer.parseInt(noIndex)+1);
      newNo = type + dbDate + noIndexAfter;
    }
    jdbcTemplate.update("update unique_key set no=? where type=?", newNo, type);
    return newNo;
  }
}
